package com.hyphenate.easeui.ui;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.e.library.activity.EActivity;
import com.e.library.widget.ETitleBar;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.R;
import com.hyphenate.easeui.map.GLocation;
import com.hyphenate.easeui.utils.EaseCommonUtils;

import java.util.List;

/**
 * 分享位置
 * Created by e on 2017/8/15.
 */

public class EaseLocationShareActivity extends EActivity implements OnMapReadyCallback,EMMessageListener{

    public static final String TAG = "GLocation";

    private ETitleBar titleBar;
    private GoogleMap mMap;
    private GLocation gLocation;

    protected String toChatUsername;
    private Marker mMarker1;//我的Marker
    private Marker mMarker2;//对方的Marker

    @Override
    protected int layout() {
        return R.layout.activity_location_share;
    }

    @Override
    protected void onActivityCreated(Bundle state) {

        toChatUsername = getIntent().getStringExtra(EaseConstant.EXTRA_USER_ID);

        titleBar = (ETitleBar) findViewById(R.id.title_bar);
        gLocation = new GLocation(this){
            @Override
            protected void successful(double lng, double lat) {
                super.successful(lng, lat);

                if(mMarker1 !=null) {
                    mMarker1.remove();
                    mMarker1 = null;
                }

                LatLng latLng = new LatLng(lat, lng);
                mMarker1 = mMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_location_marker)));

                /**正在发送位置*/
                EMMessage message = message(EaseConstant.TYPE_SHARE_LOCATION);
                message.setAttribute("longitude",String.valueOf(lng));
                message.setAttribute("latitude",String.valueOf(lat));
                EMClient.getInstance().chatManager().sendMessage(message);
            }

            @Override
            protected void failure() {
                super.failure();
            }
        };

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
        mMap.setTrafficEnabled(true);
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.getUiSettings().setZoomGesturesEnabled(false);
        gLocation.onMapReady(mMap);
    }

    @Override
    public void onStart() {
        super.onStart();
        gLocation.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
        gLocation.onStop();
        EMClient.getInstance().chatManager().removeMessageListener(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        gLocation.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        gLocation.onResume();
        EMClient.getInstance().chatManager().addMessageListener(this);
    }

    @Override
    protected void onDestroy() {
        EMMessage message = message(EaseConstant.TYPE_SHARE_LOCATION_END);
        EMClient.getInstance().chatManager().sendMessage(message);
        super.onDestroy();
    }

    private EMMessage message(int type){
        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.CMD);
        message.setTo(toChatUsername);
        String action = String.valueOf(type);
        EMCmdMessageBody cmdBody = new EMCmdMessageBody(action);
        message.addBody(cmdBody);
        message.setChatType(EMMessage.ChatType.Chat);
        EaseCommonUtils.putUser(this,message);
        EaseCommonUtils.putType(message,type);
        return message;
    }

    private double toDouble(String str){
        if(TextUtils.isEmpty(str)) {
            return 0;
        }
        try {
            return Double.parseDouble(str);
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        gLocation.onRequestPermissionsResult(requestCode,permissions,grantResults);
    }

    @Override
    public void onMessageReceived(List<EMMessage> list) {

    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> messages) {
        for (EMMessage message:messages){
            int type = EaseCommonUtils.type(message);
            switch (type){
                case EaseConstant.TYPE_SHARE_LOCATION:
                    if(message.direct() == EMMessage.Direct.RECEIVE) {
                        String longitude = message.getStringAttribute("longitude","");
                        String latitude = message.getStringAttribute("latitude","");
                        double lng = toDouble(longitude);
                        double lat = toDouble(latitude);
                        if(lat == 0 || lng == 0) {
                            return;
                        }
                        if(mMarker2 != null) {
                            mMarker2.remove();
                            mMarker2 = null;
                        }
                        LatLng latLng = new LatLng(lat, lng);
                        mMarker2 = mMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_location_marker)));
                    }
                    break;
                case EaseConstant.TYPE_SHARE_LOCATION_START:

                    break;
                case EaseConstant.TYPE_SHARE_LOCATION_END:
                    break;
            }
        }
    }

    @Override
    public void onMessageRead(List<EMMessage> list) {

    }

    @Override
    public void onMessageDelivered(List<EMMessage> list) {

    }

    @Override
    public void onMessageRecalled(List<EMMessage> list) {

    }

    @Override
    public void onMessageChanged(EMMessage emMessage, Object o) {

    }
}
